
<template>

    <el-main>
  
      <el-form
          :model="searchModel"
          ref="searchForm"
          label-width="80px"
          :inline="true"
          size="small"
          >
          <el-form-item>
          <el-input v-model="searchModel.apiName" placeholder="请输入API名称"/>
          </el-form-item>
          <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
          <el-button icon="el-icon-refresh-right">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="openAddWindow()">新增</el-button>
          </el-form-item>
      </el-form>
          <!-- 数据表格 -->
          <el-table
          :data="tableData"
          border
          style="width: 100%">
            <el-table-column
                prop="id"
                label="id"
                width="70"
                align="center">
              </el-table-column>
              <el-table-column
                prop="apiName"
                label="网址名字"
                width="100"
                align="center">
              </el-table-column>

              <el-table-column
                prop="requestUrl"
                label="请求地址"
                width="400"
                align="center">
              </el-table-column>
              
              <el-table-column
                prop="rowTypeCondition"
                label="参数种类"
              
                align="center">
                 <template  slot-scope="scope">
                    <el-select 
                    :ref="'optionRef'+ scope.$index"
                    v-model="selectConditionType[scope.$index].value"  
                    @focus="showCities()" 
                    placeholder="请选择">
                        <el-option
                        v-for="item in scope.row.types"
                        :key="item.typeId"
                        :label="item.typeName"
                        :value="item.typeId">
                        </el-option>
                    </el-select>
                 </template>
              </el-table-column>

              <el-table-column
                prop="cities"
                label="参数"
                align="center">
                <template slot-scope="scope">
                  <el-cascader
                    :ref="'cascaderRef'+ scope.$index"
                    :options="conditionValue[scope.$index].cities"
                    :props="defaultCityProps"
                    clearable>
                    </el-cascader>
                  </template>
                  
              </el-table-column>
  
              <el-table-column label="操作" align="center" width="280">
                <template slot-scope="scope">
                    <el-button
                    icon="el-icon-s-promotion"
                    type="primary"
                    size="small"
                    @click="handleTest(scope.row.id,scope.row.requestUrl,scope.$index)"
                    >测试请求
                    </el-button>
  
                    <el-button
                    icon="el-icon-document-copy"
                    type="danger"
                    size="small"
                    @click="openMappingWindow(scope.row.id)"
                    >JSON字段映射
                    </el-button>
  
                 </template>
              </el-table-column>
    
      </el-table>
      <!-- 分页工具栏 -->
      <el-pagination
      background

      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      >
      </el-pagination>
  
       <!-- json映射配置窗口 -->
       <system-dialog
        :title="jsonDialog.title"
        :visible="jsonDialog.visible"
        :width="jsonDialog.width"
        :height="jsonDialog.height"
        @onClose="onClose()"
        @onConfirm="onConfirm()"
      >

      <div slot="content">
      
          <json-viewer 
          :value="jsonResult[resultKey]"
          :expand-depth=5
          copyable
          >
          </json-viewer>
          <p/>
          <el-form
            :model="jsonMapWeather"
            ref="mappingForm"
            label-width="120px"
            :inline="true"
            size="small">

            <el-form-item label="weatherApiId" prop="weatherApiId">
            <el-input v-model="jsonMapWeather.weatherApiId" :readonly="true" @click.native="openParentAddWindow()"></el-input>
            </el-form-item>
            <el-form-item label="今日请求次数" prop="nums">
            <el-input v-model="jsonMapWeather.nums" placeholder="nums"></el-input>
            </el-form-item>
            <el-form-item label="城市ID"  prop="cityId">
            <el-input v-model="jsonMapWeather.cityId" placeholder="cityId"></el-input>
            </el-form-item>
            <el-form-item label="城市名称" prop="city">
            <el-input v-model="jsonMapWeather.city" placeholder="city"></el-input>
            </el-form-item>
            <el-form-item label="当前日期" prop="date">
            <el-input v-model="jsonMapWeather.date" placeholder="date"></el-input>
            </el-form-item>
            <el-form-item label="星期" prop="week">
            <el-input v-model="jsonMapWeather.week" placeholder="week"></el-input>
            </el-form-item>
            <el-form-item label="更新时间" class="item" prop="updateTime">
            <el-input v-model="jsonMapWeather.updateTime" placeholder="updateTime"></el-input>
            </el-form-item>
            <el-form-item label="天气情况" class="item" prop="wea">
            <el-input v-model="jsonMapWeather.wea" placeholder="wea"></el-input>
            </el-form-item>
            <el-form-item label="天气图片" prop="weaImg">
            <el-input v-model="jsonMapWeather.weaImg" placeholder="weaImg"></el-input>
            </el-form-item>
            <el-form-item label="实况温度" class="item" prop="tem">
            <el-input v-model="jsonMapWeather.tem" placeholder="tem"></el-input>
            </el-form-item>
            <el-form-item label="白天温度" class="item" prop="temDay">
            <el-input v-model="jsonMapWeather.temDay" placeholder="temDay"></el-input>
            </el-form-item>
            <el-form-item label="夜间温度" class="item" prop="temNight">
            <el-input v-model="jsonMapWeather.temNight" placeholder="temNight"></el-input>
            </el-form-item>
            <el-form-item label="风向"  class="item" prop="win">
            <el-input v-model="jsonMapWeather.win" placeholder="win"></el-input>
            </el-form-item>
            <el-form-item label="风力" class="item" prop="winSpeed">
            <el-input v-model="jsonMapWeather.winSpeed" placeholder="winSpeed"></el-input>
            </el-form-item>
            <el-form-item label="风速" prop="winMeter">
            <el-input v-model="jsonMapWeather.winMeter" placeholder="winMeter"></el-input>
            </el-form-item>
            <el-form-item label="空气质量" prop="air">
            <el-input v-model="jsonMapWeather.air" placeholder="air"></el-input>
            </el-form-item>
            <el-form-item label="气压" prop="pressure">
            <el-input v-model="jsonMapWeather.pressure" placeholder="pressure"></el-input>
            </el-form-item>
            <el-form-item label="湿度" prop="humidity">
            <el-input v-model="jsonMapWeather.humidity" placeholder="humidity"></el-input>
            </el-form-item>
        
          </el-form>
      </div> 
    
      </system-dialog>
      
  
    </el-main> 
  
  </template> 
  
  <script>
  import SystemDialog from '@/components/system/Systemdialog';
  import weatherApi from '@/api/resource/weather';
  import roleApi from '@/api/system/role';
  import jmwApi from '@/api/resource/json-map-weather'
  //导入token
  import {getToken} from '@/utils/auth'
  export default {
    name: "weather-api",
    components:{
        SystemDialog
      },
    data() {
      return {
        searchModel :{
            belongs: this.$store.getters.userId,
            apiName: '',
            pageNo: 1,
            pageSize: 10,
        },
  
        tableData: [],//表格数据
        selectConditionType: [],//选择数据(条件类型)
        conditionValue: [] , //条件的值
        isLoaded: false, //是否加载cities
        rowTypeCondition:{} ,
        cityTree:[],
        tableHeight: 0, //表格高度
        pageNo: 1, //当前页码
        pageSize: 10, //每页显示数量
        total: 0, //总数量
        //上传需要携带的数据
        uploadHeader:{"Authorization":getToken()},
        roleIds: [], //角色ID
        userId : this.$store.getters.userId,
  
        jsonDialog: {
            title: "",      //窗口标题
            visible: false, //是否显示窗口
            width: 700,      //窗口宽度
            height: 420,    //窗口高度们
        },
        //树节点属性
        defaultCityProps: {
            children: 'children',
            label: 'cityZh',
            value: 'id',
            checkStrictly: true 
         }, 
        //测试返回结果
        jsonResult : {},
        //寻找jsonResult的索引
        resultKey:'',
        //jsonMapWeather
        jsonMapWeather:{
            id: '',
            weatherApiId: '',     // weatherApiId无需映射字段
            nums: '',            //今日实时请求次数
            cityId:    '' ,
            city:    '' ,
            date:    '' ,         //当前日期
            week:    '' ,
            updateTime:    '' ,   //更新时间
            wea:    '' ,          //天气情况
            weaImg:    '' ,      //天气图片
            tem:    '' ,        //实况温度
            temDay:    '' ,     //白天温度(高温)
            temNight:    '' ,   //夜间温度(低温)
            win:    '' ,        //风向
            winSpeed:    '' ,   //风力
            winMeter:    '' ,   //风速
            air:    '' ,        //空气质量
            pressure:    '' ,   //气压
            humidity:    '' ,   //湿度
        }, 
        // 查询结果
        jsonMapWeatherResult:{},
      }
    },
    methods :{
        //展示条件 
       async showCities(index){
 
             if( this.isLoaded ){
               this.$message.success("已加载城市")
               return ;
             }           
            //  设置角色ID
            let response = await roleApi.getUserAllRolesApi({'userId':this.userId});

            if(response.success){
                    this.roleIds = response.data;
            }
            //构建参数
            let params = {
                roleIds: this.roleIds,
                userId: this.userId
            }
            //发送查询请求
            let res = await weatherApi.getAssignUserWeatherTreeApi(params)
             //判断是否成功
            if (res.success) {
                for(let i = 0 ; i < this.tableData.length ;i++){
                  this.conditionValue[i] = {'cities': res.data.cityList} ;
                }
                this.isLoaded = true ;
                this.$message.success("城市加载成功")
            }    
        },
          /**
           *  id是weatherApi的id
            * 打开配置json -> java Object 窗口
            */
          async openMappingWindow(id) {
                //清空
                for(let index in this.jsonMapWeather){
                  this.jsonMapWeather[index] = '';
                }
                //获取映射结果
                //赋值
                this.findMapping(id);
                this.resultKey = id ;
                this.jsonMapWeather.weatherApiId = id;
                this.jsonDialog.title = 'json映射java字段'//设置窗口标题
                this.jsonDialog.visible = true//显示窗口          
            },
            /**
            * 窗口取消事件
            */
            onClose() {
                this.jsonDialog.visible = false
            },
            /**
            * 窗口确认事件
            */
            onConfirm() {
                //表单验证
                this.$refs.mappingForm.validate(async (valid)=>{
                if(valid){
                    let res = null;
                    //判断ID是否为空
                    if (this.jsonMapWeather.id === "") {
                        //新增
                        //发送添加请求
                         res = await jmwApi.addMapping(this.jsonMapWeather);
                    } else {
                        //发送修改请求
                        res = await jmwApi.editMapping(this.jsonMapWeather);
                    }
                    //判断是否成功
                    if (res.success) {
                        this.$message.success(res.message);
                        //刷新
                        this.search(this.pageNo,this.pageSize);
                        //关闭窗口
                        this.jsonDialog.visible = false;
                    } else {
                        this.$message.error(res.message);
                    }
                }
                });
  
            },
           
  
        /**
          * 测试请求
          * @param requestUrl
          */
          async  handleTest(id,requestUrl,index) {
            //使用什么类型条件查询
            let typeId =  this.$refs['optionRef'+`${index}`].selected.value ;
            let typeName = this.$refs['optionRef'+`${index}`].selected.label ;
            //使用什么条件查询 /sendRequest
            let nodes =   this.$refs['cascaderRef'+`${index}`].getCheckedNodes()[0].pathNodes; 
            let city = nodes[nodes.length-1].data;
            //构建参数
            let params = {
              id: id ,
              requestUrl: requestUrl,
              typeId: typeId,
              
            }
         
            params['city.id'] = city.id;
            params['city.cityEn'] = city.cityEn;
            params['city.cityZh'] = city.cityZh;
            let res =  await weatherApi.sendRequest(params);
            if(res.success){
              this.$message.success('API端口可用')
              this.jsonResult[id] = JSON.parse(res.data); 
             
            }else{
              this.$message.error('API端口不可用')
            }
            
          },
          /**
          * 查询
          */
          async search() {
          
              this.searchModel.pageNo = this.pageNo;//当前页码
              this.searchModel.pageSize = this.pageSize;//每页显示数量
              //发送查询请求
              let res = await weatherApi.getRequestsApi(this.searchModel);
              //执行成功
              if (res.success) {
                  //api列表
                  this.tableData = res.data;
                  //总数量
                  this.total = res.data.total;

                  for(let i = 0 ; i < this.tableData.length; i++){
                     this.selectConditionType.push({'value':''});
                     this.conditionValue.push({'cities': ''});
                  }
                 
              }else{
                this.$message.error(res.data)
             }
          },
          // 查询映射关系
          async findMapping(weatherApiId){
            let res = await jmwApi.findMapping({'weatherApiId':weatherApiId});
            if(res.success){
               this.jsonMapWeatherResult = res.data ;
               for(let key in this.jsonMapWeatherResult) {
                      //Object.keys(this.jsonMapWeather).includes(key)
                      if(this.jsonMapWeather.hasOwnProperty(key)){
                         this.jsonMapWeather[key] = this.jsonMapWeatherResult[key]
                      }
                 }
            }else{
               this.$message.error("获取映射失败")
            }
          },
      
              
    },
      //初始化时调用
      created() {
          this.search();
      },
  
  }
  </script>
  
  <style lang="scss">
  
    .mybox{
       text-align: center;
       font-family: "Georgia", Tahoma, Sans-Serif;
       line-height: 0px;
   
    }
    .el-table .warning-row {
      background: oldlace;
    }
  
    .el-table .success-row {
      background: #f0f9eb;
    }

    .item .el-form-item__label{
     color:#f56c6c;
     font-weight:bold;
  }
 
  </style>